package com.frontop.bigdata.modules.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frontop.bigdata.modules.model.BigDataProject;
import com.frontop.bigdata.modules.mapper.BigDataProjectMapper;
import com.frontop.bigdata.modules.service.BigDataProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frontop.bigdata.util.BaiduDataUtil;
import okhttp3.*;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 大数据统计--站点列表 服务实现类
 * </p>
 *
 * @author YangJia
 * @since 2022-02-11
 */
@Service
public class BigDataProjectServiceImpl extends ServiceImpl<BigDataProjectMapper, BigDataProject> implements BigDataProjectService {
    @Override
    public void pullProjectList() {
        JSONObject result = BaiduDataUtil.requestBaidu(null);
        if(result != null){
            //获取站点列表
            JSONArray list = result.getJSONObject("body").getJSONArray("data").getJSONObject(0).getJSONArray("list");
            //遍历列表入库
            if (list != null && list.size()>0){
                List<BigDataProject> bigDataProjectList = new ArrayList<>();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (int i=0;i<list.size();i++){
                    JSONObject obj = list.getJSONObject(i);
                    //判断站点是否已经存在
                    Long site_id = obj.getLong("site_id");
                    if(getById(site_id) != null){
                        continue;
                    }
                    BigDataProject bigDataProject = new BigDataProject();
                    bigDataProject.setSiteId(site_id);
                    bigDataProject.setDomain(obj.getString("domain"));
                    //网点名称默认域名
                    bigDataProject.setProjectName(obj.getString("domain"));
                    bigDataProject.setStatus(obj.getInteger("status"));
                    try {
                        bigDataProject.setCreateTime(formatter.parse(obj.getString("create_time")));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    bigDataProjectList.add(bigDataProject);
                }
                //添加入库
                saveBatch(bigDataProjectList);
            }
        }
        System.out.println(result);
    }
}